using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.OnScreen;
using UnityEngine.Serialization;

namespace BlockOS.Client
{
    public class OnScreenRocker : OnScreenControl, IPointerDownHandler, IPointerUpHandler, IDragHandler
    {
        [SerializeField]
        private RectTransform m_HandleTransform;

        [InputControl(layout = "Vector2")]
        [SerializeField]
        private string m_ControlPath;

        private RectTransform m_rectTransform;
        public RectTransform rectTransform
        {
            get
            {
                if (m_rectTransform == null)
                {
                    m_rectTransform = GetComponent<RectTransform>();
                }
                return m_rectTransform;
            }
        }

        private Vector2 m_StartPos;

        private int m_FingerId;

        private float movementRange;

        protected override string controlPathInternal
        {
            get => m_ControlPath;
            set => m_ControlPath = value;
        }

        private void Start()
        {
            m_StartPos = m_HandleTransform.localPosition;
            movementRange = rectTransform.rect.width / 2.0f;
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            m_HandleTransform.localPosition = m_StartPos;
            SendValueToControl(Vector2.zero);
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            if (eventData == null)
                throw new System.ArgumentNullException(nameof(eventData));

            m_FingerId = eventData.pointerId;
            OnRocker(eventData);
        }

        public void OnDrag(PointerEventData eventData)
        {
            if (eventData == null)
                throw new System.ArgumentNullException(nameof(eventData));

            if (eventData.pointerId == m_FingerId) OnRocker(eventData);
        }

        private void OnRocker(PointerEventData eventData)
        {
            RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out var position);
            var delta = position - m_StartPos;

            delta = Vector2.ClampMagnitude(delta, movementRange);
            m_HandleTransform.localPosition = m_StartPos + delta;

            var newPos = new Vector2(delta.x / movementRange, delta.y / movementRange);
            SendValueToControl(newPos);
        }
    }
}
